package com.qtu.user_service.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.qtu.entity.BmInorderlist;
import com.qtu.entity.SysEmployee;
import com.qtu.user_service.entity.InorderlistMap;
import com.qtu.user_service.entity.LogisticsMap;
import com.qtu.user_service.mapper.BmInorderlistMapper;
import com.qtu.user_service.mapper.SysEmployeeMapper;
import com.qtu.user_service.mapper.SysPositionMapper;
import com.qtu.user_service.feign.OpenClient;
import com.qtu.user_service.service.SupplyService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.lang.String;

@Service
public class SupplyServiceImpl implements SupplyService {
    @Resource
    private SysEmployeeMapper sysEmployeeMapper;
    @Resource
    private SysPositionMapper sysPositionMapper;
    @Resource
    private BmInorderlistMapper bmInorderlistMapper;
    @Autowired
    private OpenClient openClient;


    private SysEmployee sysEmployee = new SysEmployee();


    /**
     * 登录
     *
     * @param username 用户名
     * @param password 密码
     * @return
     */
    @Override
    public Map<String, Object> SupplyLogin(String username, String password) {
        UUID uuid=UUID.randomUUID();
        String token =uuid.toString();
        token=token.toUpperCase();
        token=token.replaceAll("-","");
        Map<String, Object> map = new HashMap<>();
        QueryWrapper<SysEmployee> wrapper = new QueryWrapper<>();
        wrapper.eq("tel", username);
        sysEmployee = sysEmployeeMapper.selectOne(wrapper);//查询登录用户的信息
        if (sysEmployee == null) {
            map.put("msg", "用户不存在");
            return map;
        } else if (sysEmployee.getPassword().equals(password)) {//比对登录密码
            if (openClient.exists(sysEmployee.getToken()).equals("true")) {//判断是否已登录
                map.put("msg", "用户已登录");
                return map;
            } else {
                if (sysEmployee.getToken() == null || sysEmployee.getToken().equals(" ")) {//判断是否已有Token值
                    UpdateWrapper updateWrapper = new UpdateWrapper();
                    updateWrapper.eq("tel", username);
                    sysEmployee.setToken(token);//如果没有Token值则赋值
                    sysEmployeeMapper.update(sysEmployee, updateWrapper);
                    if (openClient.setByTime(sysEmployee.getToken(), sysEmployee, 2).equals("ok")) {//加入redis缓存,并设置超时时间
                        System.out.println(sysEmployee.getToken());
                        map.put("msg", sysEmployee.getToken());
                        return map;
                    } else {
                        map.put("msg", "系统繁忙");
                        return map;
                    }
                } else {
                    if (openClient.setByTime(sysEmployee.getToken(), sysEmployee, 2).equals("ok")) {
                        //加入redis缓存,并设置超时时间
                        map.put("msg", sysEmployee.getToken());
                        return map;
                    } else {
                        map.put("msg", "系统繁忙");
                        return map;
                    }
                }
            }
        } else {
            map.put("msg", "密码错误");
            return map;
        }
    }


    @Override
    public Map<String, Object> getEmployee(String tel, String token) {
        SysEmployee sysEmployee=new SysEmployee();
        QueryWrapper<SysEmployee> wrapper=new QueryWrapper<>();
        wrapper.eq("tel",tel);
       sysEmployee=sysEmployeeMapper.selectOne(wrapper);
        Map<String, Object> map = new HashMap<String, Object>();
        if (openClient.exists(token).equals("true")) { //判断是否已登录
            String[] positionId = sysEmployee.getPositionId().split(",");//获取该员工的岗位
            String str = "";
            for (int i = 0; i < positionId.length; i++) {
                if (str == "") {
                    str = sysPositionMapper.selectById(positionId[i]).getPositionName();
                } else {
                    str += "," + sysPositionMapper.selectById(positionId[i]).getPositionName();
                }
            }
            sysEmployee.setPositionId(str);
            str = "";
            map.put("sys", sysEmployee);
            openClient.expire(token, 30);
            return map;
        } else {
            map.put("sys", null);
            return map;
        }
    }

    /**
     * 退出登录，删除redis中的数据
     *
     * @param token
     */
    public Map<String,Object> outlogin(String token) {
       Map<String,Object> map=new HashMap<>();
       if (openClient.delete(token).equals("success")){
           map.put("out","success");
           return map;
       }else {
           return null;
       }
    }

    /**
     * 修改密码
     *
     * @param username    手机号
     * @param oldPassword 旧密码
     * @param newPassword 新密码
     * @param token
     * @return
     */
    @Override
    public Integer updatePassword(String username, String oldPassword, String newPassword, String token) {
        if (sysEmployee.getPassword().equals(oldPassword) && openClient.exists(token).equals("true")) {
            UpdateWrapper wrapper = new UpdateWrapper();
            wrapper.eq("tel", username);
            sysEmployee.setPassword(newPassword);
            Integer i = sysEmployeeMapper.update(sysEmployee, wrapper);
            openClient.expire(token, 30);
            return i;
        } else if (!sysEmployee.getPassword().equals(oldPassword) && openClient.exists(token).equals("true")) {
            openClient.expire(token, 30);
            return 0;
        } else {
            return 2;
        }
    }

    @Override
    public Map<String, Object> getInorderlist(String username, String token) {
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("tel", username);
        sysEmployee = sysEmployeeMapper.selectOne(wrapper);
        Map<String, Object> map = new HashMap<>();
        if (openClient.exists(token).equals("true")) {
            Integer id = sysEmployee.getId();
            String[] Id = sysEmployee.getPositionId().split(",");
            Integer min = Integer.parseInt(Id[0]);
            for (int i = 0; i < Id.length; i++) {
                Integer s = Integer.parseInt(Id[i]);
                min = s < min ? s : min;
            }
            if (min == 1) {//用户为经理，可以看到所有
                map.put("amount", sysEmployeeMapper.getAmount(null, id));
                map.put("amountDay", sysEmployeeMapper.getAmountDay(null, id));
                return map;
            } else {
                Integer[] Member = new Integer[10];
                InorderlistMap inorderlistMap1 = new InorderlistMap();
                InorderlistMap inorderlistMap = new InorderlistMap();
                try {
                    inorderlistMap = sysEmployeeMapper.getAmount(min, id);
                    inorderlistMap1 = sysEmployeeMapper.getAmountDay(min, id);
                    System.err.println(inorderlistMap1.getAmount());
                    Member = new Integer[]{sysEmployeeMapper.getMember(username), sysEmployeeMapper.getMember1(min, id)};
                } catch (Exception e) {
                    e.printStackTrace();
                }
                if (inorderlistMap1.getAmount()==null) {
                    inorderlistMap1.setAmount(0.0);
                }
                if (inorderlistMap1.getNumber() == null) {
                    inorderlistMap1.setNumber(0);
                }
                if (inorderlistMap.getAmount() == null) {
                    inorderlistMap.setAmount(0.0);// 月款
                }
                if (inorderlistMap.getNumber() == null) {
                    inorderlistMap.setNumber(0);
                }
                if (inorderlistMap.getBuyNum() == null) {
                    inorderlistMap.setBuyNum(0);
                }
                if (Member[0] == null) {
                    Member[0] = 0;
                }
                if (Member[1] == null) {
                    Member[1] = 0;
                }
                map.put("amount", inorderlistMap);//用户为员工只能看到自己的
                map.put("amountDay", inorderlistMap1.getAmount());
                map.put("OrderDayNumber", inorderlistMap1.getNumber());
                map.put("OrderNoDistribution", sysEmployeeMapper.getOrder(2, null, min, id));
                map.put("OrderNoDeliver", sysEmployeeMapper.getOrder(3, 5, min, id));
                map.put("OrderDelivery", sysEmployeeMapper.getOrder(null, 6, min, id));
                map.put("Member", Member);
                openClient.expire(token, 30);
                return map;
            }
        } else {
            map.put("amount", "已退出登录");
            return map;
        }
    }

    @Override
    public Map<String, Object> getlogistics(String num,String num1,String token, String username) {
        System.out.println("物流");
        Map<String, Object> map = new HashMap<>();
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("tel", username);
        sysEmployee = sysEmployeeMapper.selectOne(wrapper);
        if (openClient.exists(token).equals("true")) {
            Integer id = sysEmployee.getId();
            String[] Id = sysEmployee.getPositionId().split(",");
            Integer min = Integer.parseInt(Id[0]);
            for (int i = 0; i < Id.length; i++) {
                Integer s = Integer.parseInt(Id[i]);
                min = s < min ? s : min;
            }
            List<LogisticsMap> logisticsMaps=new ArrayList<>();
            if (min==1){
                try {
                    logisticsMaps = sysEmployeeMapper.getLogistics(num,num1,null,null);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                map.put("logis",logisticsMaps);
                return map;
            }else {
                try {
                    if (num1==null){
                        logisticsMaps = sysEmployeeMapper.getLogistics(num, num1, min, id);
                    }else {
                        logisticsMaps = sysEmployeeMapper.getLogistics(num, num1, min, id);
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                }
                for (LogisticsMap logisticsMap:logisticsMaps){
                    logisticsMap.setPosition(min);
                }
                map.put("logis", logisticsMaps);
                System.out.println(logisticsMaps);
                openClient.expire(token, 30);
                return map;
            }
        }
        map.put("logis","未登录");
        return map;
    }

    @Override
    public Map<String,Object> updateOrderStep(Integer num,String orderId, String token) {
        System.err.println(num);
        Map<String,Object> map=new HashMap<>();
        UpdateWrapper wrapper = new UpdateWrapper();
        wrapper.eq("orderId",orderId);
        if (openClient.exists(token).equals("true")){
            BmInorderlist bmInorderlist=new BmInorderlist();
            bmInorderlist.setOrderStep(num);
            Integer Total=bmInorderlistMapper.update(bmInorderlist,wrapper);
            if ((Total!=null||Total!=0)){
                map.put("number",bmInorderlist.getOrderStep());
                openClient.expire(token, 30);
                return map;
            }else {
                map.put("number",null);
                openClient.expire(token, 30);
                return map;
            }
        }
        map.put("number",null);
        openClient.expire(token, 30);
        return map;
    }

    @Override
    public Map<String, Object> getGoods(Integer orderId, String token) {
        Map<String,Object> map=new HashMap<>();
        if (openClient.exists(token).equals("true")){
            List<LogisticsMap> logisticsMaps= sysEmployeeMapper.getGoods(orderId);
            map.put("Goods",logisticsMaps);
            openClient.expire(token,30);
            return map;
        }else {
            map.put("Goods",null);
            return map;
        }
    }

    @Override
    public Map<String, Object> getEmployees(String token) {
        System.err.println(token);
        Map<String,Object> map = new HashMap<>();

        if (openClient.exists(token).equals("true")){
            Object object =openClient.get(token);
            map.put("eply",object);
            return map;
        }else {
            map.put("eply",null);
            return map;
        }
    }


    public Integer updateLogisticsId(Integer orderId){
        Integer a=0;
       String warehouseCode = sysEmployeeMapper.getWarehouseCode(orderId);
        if (sysEmployeeMapper.getDispatch(warehouseCode)==null){
                sysEmployeeMapper.addDispatch(warehouseCode);
                updateLogisticsId(orderId);
        }else if (sysEmployeeMapper.getDispatch(warehouseCode).equals("1")){
           a=updateLogisticsId1(orderId,warehouseCode);
        }else if (sysEmployeeMapper.getDispatch(warehouseCode).equals("2")){
            a=updateLogisticsId2(orderId);
        }
        return a;
    }
    @Override
    public Integer updateLogisticsId1(Integer orderId,String warehouseCode) {
       Integer LogisticsId=sysEmployeeMapper.getMinLogisticsId(warehouseCode);
        if (LogisticsId==null){
            return 0;
        }
       Integer update=sysEmployeeMapper.updateLogisticsId(LogisticsId,orderId);
        return update;
    }
    Integer s=0;

    @Override
    public Integer updateLogisticsId2(Integer orderId){
        Integer a=0;
        String[] Id=sysEmployeeMapper.getId(orderId);
        Integer maxId= sysEmployeeMapper.getMaxId(orderId);
            if (s==maxId){
                s=0;
            }else {
                for (int i = 0; i <Id.length ; i++) {
                    s=Integer.parseInt(Id[i]);
                }

                System.err.println(s);
               a= sysEmployeeMapper.updateLogisticsId(s,orderId);
            }
        return a;
    }

}